package org.example.fancystudy.atomics;

import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.LongBinaryOperator;

/**
 * @author chaigq
 * @version 1.0
 * @date 2023/2/20 11:41
 */
public class LongAdderAPIDemo {
    public static void main(String[] args) {
        LongAdder longAdder = new LongAdder();
        longAdder.increment();
        longAdder.increment();
        longAdder.add(5);
        longAdder.decrement();
        System.out.println(longAdder.sum());
        longAdder.doubleValue();// 将long转换为double类型
        longAdder.floatValue();// 将long转换为float类型
        longAdder.intValue();// 将long转换为int类型
        longAdder.reset(); // 重置为0
        System.out.println(longAdder.toString());

        // 初始化 LongAccumulator 对象
        LongAccumulator longAccumulator = new LongAccumulator((x,y) -> x * y, 1);
        // 另一种方式初始化 LongAccumulator 对象
        LongAccumulator longAccumulator1 = new LongAccumulator(new LongBinaryOperator() {
            @Override
            public long applyAsLong(long left, long right) {
                return left + right;
            }
        }, 0);
        longAccumulator.accumulate(3);
        longAccumulator.accumulate(3);
        System.out.println(longAccumulator.get());
    }
}
